package net.crazyblock.mobilesafe;

import java.util.ArrayList;
import java.util.List;

import net.crazyblock.mobilesafe.domain.AppInfo;
import net.crazyblock.mobilesafe.engin.AppInfoProvider;
import net.crazyblock.mobilesafe.utils.DensityUtil;

import android.R.integer;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.text.format.Formatter;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class AppManagerActivity extends Activity implements OnClickListener {
	private ListView lv_app_manager;
	private List<AppInfo> appInfos;
	private List<AppInfo> userAppInfos;
	private List<AppInfo> sysAppInfos;
	private LinearLayout loading;
	private TextView status;
	private TextView tv_avail_rom;
	private TextView tv_avail_sd;
	private PopupWindow popupWindow;
	private LinearLayout ll_start;
	private LinearLayout ll_uninstall;
	private LinearLayout ll_share;
	/**
	 * 被点击条目的appInfo
	 */
	private AppInfo appInfo;
	private AppInfosListAdapter lv_adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_app_manager);

		setAvailableSpaceInfo();
		status = (TextView) findViewById(R.id.tv_statue);
		lv_app_manager = (ListView) findViewById(R.id.list_app_infos);
		loading = (LinearLayout) findViewById(R.id.loading);

		loading.setVisibility(View.VISIBLE);
		fillData();

		lv_app_manager.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				dismissPopupWindow();
				if (userAppInfos != null && sysAppInfos != null) {
					status.setVisibility(View.VISIBLE);
					if (firstVisibleItem > userAppInfos.size()) {
						status.setText("系统程序：" + sysAppInfos.size() + "个");
					} else {
						status.setText("用户程序：" + userAppInfos.size() + "个");
					}
				}

			}
		});
		lv_app_manager.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (position == 0) {
					return;
				} else if (position == (userAppInfos.size() + 1)) {
					return;
				} else if (position <= userAppInfos.size()) {
					int newPosition = position - 1;
					appInfo = userAppInfos.get(newPosition);
				} else {
					int newPosition = position - userAppInfos.size() - 2;
					appInfo = sysAppInfos.get(newPosition);
				}
				dismissPopupWindow();
				View contentView = View.inflate(AppManagerActivity.this,
						R.layout.popup_app_item, null);
				ll_start = (LinearLayout) contentView
						.findViewById(R.id.ll_start);
				ll_share = (LinearLayout) contentView
						.findViewById(R.id.ll_share);
				ll_uninstall = (LinearLayout) contentView
						.findViewById(R.id.ll_uninstall);
				ll_start.setOnClickListener(AppManagerActivity.this);
				ll_share.setOnClickListener(AppManagerActivity.this);
				ll_uninstall.setOnClickListener(AppManagerActivity.this);
				// TextView contentView = new TextView(getApplicationContext());
				// contentView.setText(appInfo.getPackName());
				popupWindow = new PopupWindow(contentView, -2, -2);
				// popupwindow显示动画需要有背景
				popupWindow.setBackgroundDrawable(new ColorDrawable(
						Color.TRANSPARENT));
				int[] location = new int[2];
				view.getLocationInWindow(location);
				int dipValue = 60;
				int pxValue = DensityUtil.dip2px(AppManagerActivity.this,
						dipValue);
				popupWindow.showAtLocation(parent, Gravity.LEFT | Gravity.TOP,
						pxValue, location[1]);
				ScaleAnimation sa = new ScaleAnimation(0.3f, 1.0f, 0.3f, 1.0f,
						Animation.RELATIVE_TO_SELF, 0,
						Animation.RELATIVE_TO_SELF, 0.5f);
				sa.setDuration(300);
				AlphaAnimation aa = new AlphaAnimation(0.5f, 1.0f);
				aa.setDuration(300);
				AnimationSet set = new AnimationSet(false);
				set.addAnimation(sa);
				set.addAnimation(aa);
				contentView.startAnimation(set);
			}
		});
	}

	private void setAvailableSpaceInfo() {
		tv_avail_rom = (TextView) findViewById(R.id.tv_avail_rom);
		tv_avail_sd = (TextView) findViewById(R.id.tv_avail_sd);
		long sdsize = getAvailSpace(Environment.getExternalStorageDirectory()
				.getAbsolutePath());
		long romsize = getAvailSpace(Environment.getDataDirectory()
				.getAbsolutePath());
		tv_avail_sd
				.setText("外存可用空间：" + Formatter.formatFileSize(this, sdsize));
		tv_avail_rom.setText("内存可用空间："
				+ Formatter.formatFileSize(this, romsize));

	}

	/**
	 * 填充数据操作
	 */
	private void fillData() {
		new Thread() {
			public void run() {
				appInfos = AppInfoProvider.getAppinfos(AppManagerActivity.this);
				userAppInfos = new ArrayList<AppInfo>();
				sysAppInfos = new ArrayList<AppInfo>();
				for (AppInfo appInfo : appInfos) {
					if (appInfo.isUserApp()) {
						userAppInfos.add(appInfo);
					} else {
						sysAppInfos.add(appInfo);
					}
				}
				runOnUiThread(new Runnable() {
					public void run() {
						if (lv_adapter == null) {
							lv_adapter = new AppInfosListAdapter();
							lv_app_manager.setAdapter(lv_adapter);
						} else {
							lv_adapter.notifyDataSetChanged();
						}

						loading.setVisibility(View.INVISIBLE);
					}
				});

			}

		}.start();
	}

	private void dismissPopupWindow() {
		if (popupWindow != null && popupWindow.isShowing()) {
			popupWindow.dismiss();
			popupWindow = null;
		}
	}

	@Override
	protected void onDestroy() {
		dismissPopupWindow();
		super.onDestroy();
	}

	private class AppInfosListAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return appInfos.size() + 2;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			AppInfo appInfo;
			View view;
			ViewHolder holder;

			if (position == 0) {
				TextView tv = new TextView(AppManagerActivity.this);
				tv.setBackgroundColor(Color.GRAY);
				tv.setTextColor(Color.WHITE);
				tv.setTextSize(20);
				tv.setText("用户程序:" + userAppInfos.size() + "个");
				return tv;
			} else if (position == userAppInfos.size() + 1) {
				TextView tv = new TextView(AppManagerActivity.this);
				tv.setBackgroundColor(Color.GRAY);
				tv.setTextColor(Color.WHITE);
				tv.setTextSize(20);
				tv.setText("系统程序:" + sysAppInfos.size() + "个");
				return tv;
			} else if (position < userAppInfos.size() + 1) {
				int newPosition = position - 1;
				appInfo = userAppInfos.get(newPosition);
			} else {
				int newPosition = position - userAppInfos.size() - 2;
				appInfo = sysAppInfos.get(newPosition);
			}

			if (convertView != null && convertView instanceof RelativeLayout) {
				view = convertView;
				holder = (ViewHolder) view.getTag();
			} else {
				view = View.inflate(AppManagerActivity.this,
						R.layout.list_item_appinfo, null);
				holder = new ViewHolder();
				holder.appIcon = (ImageView) view
						.findViewById(R.id.iv_app_icon);
				holder.appName = (TextView) view.findViewById(R.id.tv_app_name);
				holder.appLocation = (TextView) view
						.findViewById(R.id.tv_app_location);
				view.setTag(holder);
			}
			holder.appIcon.setImageDrawable(appInfo.getIcon());
			holder.appName.setText(appInfo.getName());
			if (appInfo.isInRom()) {
				holder.appLocation.setText("内部存储");
			} else {
				holder.appLocation.setText("外部存储");
			}

			return view;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

	}

	static class ViewHolder {
		TextView appName;
		TextView appLocation;
		ImageView appIcon;
	}

	// 弹出悬浮窗体对应布局的点击事件
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ll_start:
			// start app
			startApplication();
			break;
		case R.id.ll_uninstall:
			// uninstall app
			if (appInfo.isUserApp()) {
				uninstallApplication();
			} else {
				Toast.makeText(this, "需要Root权限", 0).show();
			}

			break;
		case R.id.ll_share:
			// share app
			shareApplication();
			break;

		}
	}

	private void shareApplication() {
		dismissPopupWindow();
		Intent intent = new Intent();
		intent.setAction("android.intent.action.SEND");
		intent.addCategory(Intent.CATEGORY_DEFAULT);
		intent.setType("text/plain");
		intent.putExtra(Intent.EXTRA_TEXT, "推荐您使用一款软件：" + appInfo.getName());
		startActivity(intent);
	}

	/**
	 * 卸载应用
	 */
	private void uninstallApplication() {
		dismissPopupWindow();
		Intent intent = new Intent();
		intent.setAction("android.intent.action.VIEW");
		intent.setAction("android.intent.action.DELETE");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.setData(Uri.parse("package:" + appInfo.getPackName()));
		startActivityForResult(intent, 0);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		fillData();
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 开启应用
	 */
	private void startApplication() {
		dismissPopupWindow();
		PackageManager pm = getPackageManager();
		Intent intent = pm.getLaunchIntentForPackage(appInfo.getPackName());
		if (intent != null) {
			startActivity(intent);
		} else {
			Toast.makeText(this, "无法启动该应用", 0).show();
		}
	}

	/**
	 * 获取某个目录的可用空间
	 * 
	 * @param path
	 * @return
	 */
	private long getAvailSpace(String path) {
		StatFs statf = new StatFs(path);
		statf.getBlockCount();// 获取分区的个数
		long size = statf.getBlockSize();// 获取分区的大小
		long count = statf.getAvailableBlocks();// 获取可用的区块的个数
		return size * count;
	}
}
